package com.coolwen.springmvc.service;


import com.coolwen.springmvc.dao.IGroupDao;
import com.coolwen.springmvc.dao.IUserDao;
import com.coolwen.springmvc.exception.UserException;
import com.coolwen.springmvc.model.Group;
import com.coolwen.springmvc.model.User;
import com.coolwen.springmvc.model.UserGroupDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author CoolWen
 * @version 2018-10-12 10:56
 */
@Service("userService")
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService {
    @Autowired
    private IUserDao userDao;

    @Autowired
    private IGroupDao groupDao;

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void add(User u, int gid) {
        Group g = groupDao.load(gid);
        System.out.println(g);
        if (g == null) {
            throw new UserException("添加的用户组不存在");
        }
        u.setGid(gid);
        userDao.add(u);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void delete(int id) {
        userDao.delete(id);
    }

    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void update(User u, int gid) {
        Group g = groupDao.load(gid);
        if (g == null) {
            throw new UserException("更新的用户组不存在");
        }
        u.setGid(gid);
        userDao.update(u);
    }

    @Override
    public User load(int id) {
        return userDao.load(id);
    }

    @Override
    public List<UserGroupDto> listAllUser() {


        return userDao.listUserGroupDto();
    }

    @Override
    public List<User> listByGroup(int gid) {
        return userDao.list("from User where gid=?", gid);
    }

    @Override
    public User login(String username, String password) {
        User u = userDao.loadByName(username);
        if (u == null) {
            throw new UserException("用户名或者密码错误");
        }
        if (!u.getPassword().equals(password)) {
            throw new UserException("用户名或者密码错误");
        }
        return u;
    }

    /***
     * 测试事务管理
     * @param group
     * @param user
     */
    @Override
    @Transactional(readOnly = false, propagation = Propagation.REQUIRES_NEW)
    public void addGroupAndUser(Group group, User user) {
        groupDao.add(group);
        int i = 1 / 0;
        userDao.add(user);
//        try {
//            userDao.add(user);
//        } finally {
//            throw new UserException("加不进去了！");
//        }
    }


}
